﻿using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EachRecord.Common
{
    /// <summary>
    ///   redis 作为缓存数据共享中心
    /// </summary>
  public  class RedisUtils
    {

        private static RedisUtils redisUtils { get; set; }

        private static readonly string connect = RedisConstant.REDIS_CONNECTION_STRING;
        private ConnectionMultiplexer redisConnect { get; set; }
        private IDatabase database { get; set; }

        /// <summary>
        /// 初始化redis连接
        /// </summary>
        private RedisUtils()
        {
            redisConnect = ConnectionMultiplexer.Connect(connect);
            database = redisConnect.GetDatabase();
        }

        /// <summary>
        /// 返回redis实例
        /// </summary>
        /// <returns></returns>
        public static RedisUtils Instance() {
            if (redisUtils == null) { 
                   redisUtils=new RedisUtils();
            }
            return redisUtils;
        }

        /// <summary>
        /// 添加值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool SetStringValue(string key, string value)
        {
            return database.StringSet(key,value);
        }

        /// <summary>
        /// 获取值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string GetValue(string key)
        {
            return database.StringGet(key);
        }

        /// <summary>
        /// 删除键
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool DeleteKey(string key)
        {
            return database.KeyDelete(key);
        }

        /// <summary>
        /// 提供对外扩展应用于更多场景
        /// </summary>
        /// <returns></returns>
        public IDatabase GetDatabase()
        {
            return database;
        } 
    }
}